import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Select, Switch, Button, message, Divider, Tabs } from 'antd';
import { UserOutlined, LockOutlined, BellOutlined, MailOutlined, SettingOutlined, MenuOutlined, TeamOutlined, UsergroupAddOutlined, BookOutlined, FileTextOutlined } from '@ant-design/icons';
import { updateUserProfile, getSystemSettings, updateSystemSettings } from '../services/api';
import './Settings.css';

const { TabPane } = Tabs;
const { Option } = Select;

// 懒加载配置组件
const UserConfig = React.lazy(() => import('./config/UserConfig'));
const MenuConfig = React.lazy(() => import('./config/MenuConfig'));
const DepartmentConfig = React.lazy(() => import('./config/DepartmentConfig'));
const RoleConfig = React.lazy(() => import('./config/RoleConfig'));
const DictionaryConfig = React.lazy(() => import('./config/DictionaryConfig'));

const Settings = () => {
  const [userProfile, setUserProfile] = useState({});
  const [systemSettings, setSystemSettings] = useState({});
  const [loading, setLoading] = useState(true);
  const [profileForm] = Form.useForm();
  const [settingsForm] = Form.useForm();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      // 模拟获取用户信息和系统设置
      const profileData = {
        username: '管理员',
        email: 'admin@example.com',
        phone: '13800138000'
      };
      const settingsData = {
        notifications: true,
        emailNotifications: true,
        theme: 'light',
        language: 'zh-CN'
      };

      setUserProfile(profileData);
      setSystemSettings(settingsData);
      profileForm.setFieldsValue(profileData);
      settingsForm.setFieldsValue(settingsData);
    } catch (error) {
      message.error('获取数据失败');
      console.error('Failed to fetch data:', error);
    }
    setLoading(false);
  };

  const handleProfileSubmit = async (values) => {
    try {
      // 模拟更新用户信息
      await updateUserProfile(values);
      setUserProfile(values);
      message.success('用户信息更新成功');
    } catch (error) {
      message.error('更新用户信息失败');
      console.error('Failed to update profile:', error);
    }
  };

  const handleSettingsSubmit = async (values) => {
    try {
      // 模拟更新系统设置
      await updateSystemSettings(values);
      setSystemSettings(values);
      message.success('系统设置更新成功');
    } catch (error) {
      message.error('更新系统设置失败');
      console.error('Failed to update settings:', error);
    }
  };

  return (
    <div className="settings-container">
      <div className="settings-header">
        <h1>系统设置</h1>
      </div>

      <div className="settings-content">
        <Tabs defaultActiveKey="profile" tabPosition="left" style={{ height: 'calc(100vh - 120px)' }}>
          <TabPane tab={<><UserOutlined /> 个人信息</>} key="profile">
            <Card title="用户信息" className="settings-card">
          <Form
            form={profileForm}
            layout="vertical"
            onFinish={handleProfileSubmit}
            initialValues={userProfile}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
            </Form.Item>

            <Form.Item
              name="email"
              label="电子邮箱"
              rules={[
                { required: true, message: '请输入电子邮箱' },
                { type: 'email', message: '请输入有效的电子邮箱' }
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="请输入电子邮箱" />
            </Form.Item>

            <Form.Item
              name="phone"
              label="手机号码"
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
              ]}
            >
              <Input prefix={<UserOutlined />} placeholder="请输入手机号码" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                保存修改
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </TabPane>
      <TabPane tab={<><LockOutlined /> 密码设置</>} key="password">
        <Card title="密码设置" className="settings-card">
          <Form layout="vertical">
            <Form.Item
              name="oldPassword"
              label="旧密码"
              rules={[{ required: true, message: '请输入旧密码' }]}
            >
              <Input prefix={<LockOutlined />} type="password" placeholder="请输入旧密码" />
            </Form.Item>

            <Form.Item
              name="newPassword"
              label="新密码"
              rules={[
                { required: true, message: '请输入新密码' },
                { min: 6, message: '密码长度不能少于6位' }
              ]}
            >
              <Input prefix={<LockOutlined />} type="password" placeholder="请输入新密码" />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              label="确认新密码"
              rules={[
                { required: true, message: '请确认新密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newPassword') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  }
                })
              ]}
            >
              <Input prefix={<LockOutlined />} type="password" placeholder="请确认新密码" />
            </Form.Item>

            <Form.Item>
              <Button type="primary" htmlType="submit">
                修改密码
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </TabPane>
      <TabPane tab={<><SettingOutlined /> 系统参数</>} key="system">
        <Card title="系统参数" className="settings-card">
          <Form
              form={settingsForm}
              layout="vertical"
              onFinish={handleSettingsSubmit}
              initialValues={systemSettings}
            >
              <Form.Item name="notifications" label="启用通知">
                <Switch checkedChildren="开" unCheckedChildren="关" />
              </Form.Item>

              <Form.Item name="emailNotifications" label="启用邮件通知">
                <Switch checkedChildren="开" unCheckedChildren="关" />
              </Form.Item>

              <Form.Item
                name="theme"
                label="主题设置"
                rules={[{ required: true, message: '请选择主题' }]}
              >
                <Select placeholder="请选择主题">
                  <Option value="light">浅色主题</Option>
                  <Option value="dark">深色主题</Option>
                  <Option value="auto">自动切换</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="language"
                label="语言设置"
                rules={[{ required: true, message: '请选择语言' }]}
              >
                <Select placeholder="请选择语言">
                  <Option value="zh-CN">简体中文</Option>
                  <Option value="en-US">English</Option>
                </Select>
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit">
                  保存设置
                </Button>
              </Form.Item>
            </Form>
          </Card>
        </TabPane>
        <TabPane tab={<><FileTextOutlined /> 用户配置</>} key="userConfig">
          <React.Suspense fallback={<div>加载中...</div>}>
            <UserConfig />
          </React.Suspense>
        </TabPane>
        <TabPane tab={<><MenuOutlined /> 菜单配置</>} key="menuConfig">
          <React.Suspense fallback={<div>加载中...</div>}>
            <MenuConfig />
          </React.Suspense>
        </TabPane>
        <TabPane tab={<><TeamOutlined /> 部门配置</>} key="departmentConfig">
          <React.Suspense fallback={<div>加载中...</div>}>
            <DepartmentConfig />
          </React.Suspense>
        </TabPane>
        <TabPane tab={<><UsergroupAddOutlined /> 角色配置</>} key="roleConfig">
          <React.Suspense fallback={<div>加载中...</div>}>
            <RoleConfig />
          </React.Suspense>
        </TabPane>
        <TabPane tab={<><BookOutlined /> 字典配置</>} key="dictionaryConfig">
          <React.Suspense fallback={<div>加载中...</div>}>
            <DictionaryConfig />
          </React.Suspense>
        </TabPane>
      </Tabs>
      </div>
    </div>
  );
};

export default Settings;